package demo.isolib.movement {
	import demo.isolib.Tile;
	import demo.isolib.TileEvent;
	import com.sshc625.log.Logger;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import masputih.pathfinding.astar.Node;
	
	import org.casalib.util.ArrayUtil;

	/**
	 */
	public class Wander extends TileMovement {
		private var _timer:Timer;
		private var _delay:Number;
		private var _aiMove:AIMove;

		public function Wander(delay:Number, spd:uint=100) {
			_delay = delay;
			super(spd);
		}

		private function init():void {
			_tile.moveBehavior = this;
			if (_timer != null) {
				_timer.stop();
				_timer.removeEventListener(TimerEvent.TIMER_COMPLETE, pickDestination);
			}
			_timer = new Timer(_delay, 1);
			_timer.addEventListener(TimerEvent.TIMER_COMPLETE, pickDestination);
			_timer.start();
		}

		private function pickDestination(e:Event = null):void {
			var nodes:Array = tile.world.astarGrid.nodes.toArray();
			var randomNode:Node = ArrayUtil.random(nodes);
			while (randomNode.walkable == false) {
				randomNode = ArrayUtil.random(nodes);
			}

			if (_aiMove == null) {
				_aiMove = new AIMove();
				tile.addEventListener(TileEvent.CANT_MOVE, pickDestination);
				tile.addEventListener(TileEvent.MOVE_COMPLETE, onMoveComplete);
			}
			//tile.moveBehavior = new AIMove();
			tile.moveBehavior = new SmoothMove();
			tile.moveTo(randomNode.column, randomNode.row, 0);
		}


		private function onMoveComplete(e:TileEvent):void {
			init();
		}

		override public function execute(params:Array = null):void {
			Logger.log("Wander.execute(" + params + ")");
			//super.execute(params);
			init();
		}

	}

}